package cloud.shyidong.core;

import cloud.shyidong.core.constant.ErrorTypeConstant;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.util.ObjectUtils;

import java.util.LinkedHashMap;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/3/27
 */
public final class Result extends LinkedHashMap<String, Object> {
    
    public static boolean SUCCESS = true;
    
    public static Result ofData(Object data) {
        Result r = new Result();
        r.put("success", Result.SUCCESS);
        if (data != null) {
            r.put("data", data);
        }
        return r;
    }
    
    public static Result ofErrors(BusinessException... exceptions) {
        if (exceptions.length > 0) {
            Result r = new Result();
            r.put("success", !Result.SUCCESS);
            //业务错误
            if (exceptions[0].getType() == ErrorTypeConstant.BUSINESS_ERROR.getType()) {
                r.put("type", ErrorTypeConstant.BUSINESS_ERROR.getType());
                r.put("message", exceptions[0].getMessage());
                if (exceptions[0].getData() != null) {
                    r.put("data", exceptions[0].getData());
                }
            }
            //未登录
            else if (exceptions[0].getType() == ErrorTypeConstant.NO_LOGIN.getType()) {
                r.put("type", ErrorTypeConstant.NO_LOGIN.getType());
                r.put("message", ErrorTypeConstant.NO_LOGIN.getMessage());
            }
            //权限错误
            else if (exceptions[0].getType() == ErrorTypeConstant.NO_FUNCTION.getType()) {
                r.put("type", ErrorTypeConstant.NO_FUNCTION.getType());
                r.put("message", ErrorTypeConstant.NO_FUNCTION.getMessage());
            }
            //其它错误
            else {
                r.put("type", ErrorTypeConstant.SYS_ERROR.getType());
                r.put("message", ErrorTypeConstant.SYS_ERROR.getMessage());
            }
            if (exceptions[0].getMessage() != null) {
                r.put("message", exceptions[0].getMessage());
            }
            return r;
        } else {
            return ofData(null);
        }
    }
    
    public boolean isLogin() {
        Boolean success = (Boolean) this.get("success");
        if (ObjectUtils.isNull(success)) {
            return false;
        }
        if (success) {
            return true;
        }
        Integer type = (Integer) this.get("type");
        if (ErrorTypeConstant.NO_LOGIN.getType() == type.intValue()) {
            return false;
        }
        return true;
    }
    
}
